# 多阶段构建的Dockerfile
# 第一阶段：构建环境
FROM rust:1.75-slim as builder

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制Cargo文件
COPY Cargo.toml Cargo.lock ./

# 创建虚拟main.rs以缓存依赖
RUN mkdir src && echo "fn main() {}" > src/main.rs

# 构建依赖（利用Docker层缓存）
RUN cargo build --release && rm -rf src

# 复制源代码
COPY src ./src
COPY migrations ./migrations
COPY config ./config

# 构建应用
RUN cargo build --release

# 第二阶段：运行时环境
FROM debian:bookworm-slim

# 安装运行时依赖
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    libpq5 \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 创建非root用户
RUN groupadd -r appuser && useradd -r -g appuser appuser

# 设置工作目录
WORKDIR /app

# 从构建阶段复制二进制文件
COPY --from=builder /app/target/release/rust-web-service-demo /app/
COPY --from=builder /app/migrations /app/migrations
COPY --from=builder /app/config /app/config

# 创建必要的目录
RUN mkdir -p /app/logs /app/data && \
    chown -R appuser:appuser /app

# 切换到非root用户
USER appuser

# 设置环境变量
ENV RUST_LOG=info
ENV RUST_BACKTRACE=1

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:3000/health || exit 1

# 暴露端口
EXPOSE 3000 3001 3002 9090

# 启动应用
CMD ["./rust-web-service-demo"]
